package cn.fclub.print.invoice
{
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.controls.Label;
	
	import spark.components.Group;
	
	import cn.fclub.error.FclubFileException;
	import cn.fclub.print.InvoicePrinter;
	
	public class Express implements IExpress
	{
		private var _positions:XML = null;
		private var _supportNum:int = 10;
		private var _bigNumStr:String = "零壹贰参肆伍陆柒捌玖";
		private static const _SIZE_NAME:String = 'size';
		private static const _WIDTH_NAME:String = 'width';
		private static const _IF_EQUAL_NAME:String = 'ifEqual';
		private static const _IF_EQUAL_VALUE:String = '1';
		private static const _APPEND_NAME:String = 'append';
		private var  _BIG_NUM_NAME:String = 'codAmount';
		private var _WRAP_LENGTH_NAME:String='wrapLength';
		private static const _WRAP_NO_INDENT:String = 'noIndent';
		private var _invoicePrinter:InvoicePrinter = null;
		private static const EXPRESS_SF:String = 'sf';
		private var availPositoinExpress:Array = [EXPRESS_SF];
		private var invoiceConfig:InvoiceConfig = null;
		private static const _MAX_WRAP_LINE_NUM:int = 2;
		
		public function Express(ip:InvoicePrinter)
		{
			setPrinter(ip);
			super();
		}

		/**
		 * 生成一个Label 标签
		 */
		public function myLabel( data:XML, text:String='', cover:Boolean=false, j:int=0, indent:Boolean=true ):Label
		{
			var label:Label = new Label();
			var lh:int = 18;

			label.x = data.attribute('x') - ((indent&&j>0)?1:0)*18;
			label.y = data.attribute('y');
			
			if( data.attribute('lineHeight').length()>1 )
				lh=parseInt(data.attribute('lineHeight'));
			
			label.y = label.y + j*lh;
			
			if( data.attribute('width').length()>0 )
				label.width = data.attribute('width');
			if( cover )label.text = text;
			else label.text = data.toString().concat(text);//.concat(label.x,'#',label.y);
			if( data.attribute('fontSize').length()>0 )
				label.setStyle("fontSize",data.attribute('fontSize')); 

			if( data.attribute('fontWeight').length()>0 )
				label.setStyle("fontWeight",'bold'); 

			trace('label.text='+label.text);
			return label;
		}
		public function bigNum(money:int):String
		{
			var result:String="";
			var i:int = 0;
			var length:int = money.toString().length;
			while( i< length ){
				result += bigNumStr.substr(parseInt(money.toString().substr(i-length,1)), 1)+"";
				i++;
			}
			return result;
		}
		public function buildInvoiceData(data:XML):Group	
		{
			var g:Group = new Group();
		    g.s
			var size:int = parseInt(positions.@[SIZE_NAME]);
			var w:int = parseInt(positions.@[WIDTH_NAME]);
			// init group's size
			g.x=0;	g.y=size;	g.height=size; 
			if( w > size ) g.width = w;

			// loop positions and generate label's on group by incoming data
			for each ( var item:XML in positions.children() )
			{	
				var name:String = item.name().toString();
				var val:String = data.child(item.name()).toString();
				var wrap:Boolean = parseInt(item.@[WRAP_LENGTH_NAME]) > 2;
				var indent:Boolean = true;
				
				if( wrap ){
					var str:String = item.toString().concat(data.child(item.name()).toString());
					var tmpAry:Array = null;
					var j:int=0;
					item.@width = 14 * item.@[WRAP_LENGTH_NAME];
					if ( item.@[WRAP_NO_INDENT] == 'true' )indent = false;
				}
				trace(name);
				// if equal value == 指定值取得指定下面的元素
				if( String(item.@[IF_EQUAL_NAME]).length>0  )
				{
					if( item.@[IF_EQUAL_NAME].toString() == val )
					{
						trace("\t"+IF_EQUAL_NAME+':'+IF_EQUAL_VALUE);
						for each ( var subItem:XML in item.children() )
						{	trace('in for'+subItem.name());
							g.addElement( myLabel( subItem, data.child(subItem.name()).toString() ));
						}
					}
					continue;
				}

				if( String(item.@[APPEND_NAME]).length > 2 )
				{
//					trace("\tis APPEND_NAME: " + item.@[APPEND_NAME]);
					if( wrap ){						
						str = str.concat("【" + data.child(item.@[APPEND_NAME]) + '】');
						tmpAry = getSliceArray( str, item.@[WRAP_LENGTH_NAME] );
//						trace(tmpAry);
						for( ; j<tmpAry.length; j++ )
						{
							g.addElement( myLabel( item,  tmpAry[j], true,j,indent ));
						}
					}else 
					g.addElement( 
						myLabel( item,  
							data.child(item.name()).toString().concat("【" + data.child(item.@[APPEND_NAME]) + '】') ) );
					continue;
				}
				
				// normal item wrap line
				if( wrap ){
					tmpAry = getSliceArray( str, item.@[WRAP_LENGTH_NAME] );
					//						trace(tmpAry);
					for(; j<tmpAry.length; j++ )
					{
						g.addElement( myLabel( item,  tmpAry[j], true,j,indent ));
					}
					continue;
				}
				
				g.addElement( myLabel( item, data.child(item.name()) ) );
			}
			
			return g;
		}
		private function getSliceArray( str:String, len:int ):Array
		{
			trace(str)
			trace(len)
			var result:Array = [];
			for( var i:int=0; i<Math.ceil(str.length/len); i++ )
			{
				if( i==MAX_WRAP_LINE_NUM) break;
				result.push( str.slice(i*len,((i+1)==MAX_WRAP_LINE_NUM?str.length:((i+1)*len-str.length>0)?str.length:(i+1)*len)) );
			}
			return result;
		}
		
		public function setPrinter(ip:InvoicePrinter):void
		{
			invoicePrinter = ip;
		}
		/**
		 * 一个快递要有的数据，位置等数据的初始化
		 */
		public function initLayoutData(xmlFile:String):void
		{	
			if ( xmlFile == '' ){
				trace('null xml file');
				throw new FclubFileException ('null xml file');
			}else {
				readXML( xmlFile );	
			}
		}
		private function readXML( filePath:String ):void
		{
			readXML1( filePath );
		}

		private function readXML1( filePath:String ):void
		{
			var urlRequest:URLRequest = new URLRequest(filePath);
			var urlLoader:URLLoader = new URLLoader(urlRequest);
			urlLoader.addEventListener(Event.COMPLETE, readFileCompleteHandler);
		}
		private function configureListeners(dispatcher:IEventDispatcher):void {
			trace('configureListeners');
			dispatcher.addEventListener(Event.COMPLETE, readFileCompleteHandler);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			
		}
		/**
		 * 获取快递面单基本数据，坐标，以及相互依赖关系。
		 */
		private function readFileCompleteHandler(event:Event):void
		{
			trace('receive xml complete');
			positions = new XML( event.target.data );
//			trace('positions:'+positions.toXMLString());
			invoicePrinter.print();
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void {
			trace('HTTPStatusEvent');
			throw new FclubFileException('HTTPStatusEvent');
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void {
			trace('IOErrorEvent');
			throw new FclubFileException('IOErrorEvent');
		}		
		
		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace('SecurityErrorEvent');
			throw new FclubFileException('SecurityErrorEvent');
		}
		
		public function get positions():XML
		{
			return _positions;
		}
		
		public function set positions(value:XML):void
		{
			_positions = value;
		}
		
		public function get bigNumStr():String
		{
			return _bigNumStr;
		}
		
		public function set bigNumStr(value:String):void
		{
			_bigNumStr = value;
		}
		
		public function get supportNum():int
		{
			return _supportNum;
		}
		
		public function set supportNum(value:int):void
		{
			_supportNum = value;
		}

		public static function get SIZE_NAME():String
		{
			return _SIZE_NAME;
		}

		public static function get IF_EQUAL_NAME():String
		{
			return _IF_EQUAL_NAME;
		}

		public static function get IF_EQUAL_VALUE():String
		{
			return _IF_EQUAL_VALUE;
		}

		public static function get APPEND_NAME():String
		{
			return _APPEND_NAME;
		}

		public function get invoicePrinter():InvoicePrinter
		{
			return _invoicePrinter;
		}

		public function set invoicePrinter(value:InvoicePrinter):void
		{
			_invoicePrinter = value;
		}

		public function get BIG_NUM_NAME():String
		{
			return _BIG_NUM_NAME;
		}

		public function set BIG_NUM_NAME(value:String):void
		{
			_BIG_NUM_NAME = value;
		}

		public function get WRAP_LENGTH_NAME():String
		{
			return _WRAP_LENGTH_NAME;
		}

		public function set WRAP_LENGTH_NAME(value:String):void
		{
			_WRAP_LENGTH_NAME = value;
		}
		
		/**
		 * 使用系统的默认配置
		 */
		public function useSysConfig(t:String):void
		{
			invoiceConfig = new InvoiceConfig(t);
			positions = invoiceConfig.getPositions();
		}

		public static function get MAX_WRAP_LINE_NUM():int
		{
			return _MAX_WRAP_LINE_NUM;
		}

		public static function get WRAP_NO_INDENT():String
		{
			return _WRAP_NO_INDENT;
		}

		public static function get WIDTH_NAME():String
		{
			return _WIDTH_NAME;
		}


	}
}